package com.admin.service;

import com.admin.model.ActivationCode;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service
public class ActivationCodeService implements InitializingBean {

    @Value("${activation.code.length}")
    private String activationCodeLength;
    private int codeLength;
    @Value("${activation.series.length}")
    private String activationSeriesLength;
    private int seriesLength;
    private Random random = new Random();

    @Resource
    private EhCacheService ehCacheService;
    private Map<Integer, String> seriesPrefixMap = new HashMap<Integer, String>() {
        {
            this.put(0, "A");
            this.put(1, "B");
            this.put(2, "C");
            this.put(3, "D");
            this.put(4, "E");
            this.put(5, "F");
            this.put(6, "G");
            this.put(7, "H");
            this.put(8, "I");
            this.put(9, "J");
            this.put(10, "K");
            this.put(11, "L");
            this.put(12, "M");
        }
    };

    public List<ActivationCode> activationCodeGen(int num, Long takeEffectTime, Long loseEfficacyTime, Integer timeLimit, Integer price) {
        String seriesPrefix = seriesPrefixMap.get(new Date().getMonth());
        List<ActivationCode> result = new ArrayList<>();
        String batchCode = UUID.randomUUID().toString().replaceAll("-", "");
        for (int i = 0; i < num; i++) {
            String code = gen(codeLength);
            while (ehCacheService.getCodeList().contains(code)) {
                code = gen(codeLength);
            }
            String series = gen(seriesLength);
            while (ehCacheService.getSequenceList().contains(series)) {
                series = gen(seriesLength);
            }
            ActivationCode activationCode = new ActivationCode(code, seriesPrefix + series, takeEffectTime, loseEfficacyTime, timeLimit, batchCode);
            activationCode.setPrice(price);
            result.add(activationCode);
        }
        return result;
    }

    private String gen(int len) {
        StringBuilder result = new StringBuilder();
        result.append(random.nextInt(len));
        while (result.length() < len) {
            result.append(random.nextInt(9));
        }
        return result.toString();
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        seriesLength = Integer.parseInt(activationSeriesLength);
        codeLength = Integer.parseInt(activationCodeLength);

    }
}
